package edu.hubu.talentmanagementsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.CaseFormat;
import edu.hubu.talentmanagementsystem.mapper.AdminMapper;
import edu.hubu.talentmanagementsystem.mapper.PermissionMapper;
import edu.hubu.talentmanagementsystem.mapper.context.MapperContext;
import edu.hubu.talentmanagementsystem.model.ext.Admin;
import edu.hubu.talentmanagementsystem.model.ext.Role;
import edu.hubu.talentmanagementsystem.model.ext.RolePermission;
import edu.hubu.talentmanagementsystem.service.IAdminService;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import edu.hubu.talentmanagementsystem.common.EncodeOperation;
import edu.hubu.talentmanagementsystem.common.EncodeParam;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author moonlan
 * date 2021/3/2 下午8:45
 */
@SuppressWarnings(value = "unused")
@Service
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final MapperContext context;
    private final BCryptPasswordEncoder encoder;

    public AdminServiceImpl(MapperContext context, BCryptPasswordEncoder encoder) {
        this.context = context;
        this.encoder = encoder;
    }

    @Override
    public boolean deleteById(Integer id) {
        return context.getAdminMapper().deleteById(id) > 0;
    }

    @Override
    @EncodeOperation
    public Optional<Admin> insert(@EncodeParam Admin record) {
        int insert = context.getAdminMapper().insert(record);
        if (insert > 0) {
            return Optional.of(context.getAdminMapper().selectById(record.primaryKeyValue()));
        }
        return Optional.empty();
    }

    @Override
    public Optional<Admin> selectById(Integer id) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = getColumnWrapper(wrapper.lambda()).eq(Admin::getAdminId, id);
        return Optional.of(context.getAdminMapper().selectOne(lambdaQueryWrapper));
    }

    @Override
    public List<Admin> selectAll(String order) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        if (!StringUtils.hasText(order)) {
            LambdaQueryWrapper<Admin> select = getColumnWrapper(wrapper.lambda());
            return context.getAdminMapper().selectList(select);
        }
        wrapper.orderByAsc(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, order));
        LambdaQueryWrapper<Admin> select = getColumnWrapper(wrapper.lambda());
        return context.getAdminMapper().selectList(select);
    }

    @Override
    public Page<Admin> selectAllPaged(@RequestParam(required = false, defaultValue = "1") Integer currentPage,
                                      @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                                      String order) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        Page<Admin> page = new Page<>(currentPage, pageSize);
        if (!StringUtils.hasText(order)) {
            LambdaQueryWrapper<Admin> select = getColumnWrapper(wrapper.lambda());
            return context.getAdminMapper().selectPage(page, select);
        }
        wrapper.orderByAsc(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, order));
        LambdaQueryWrapper<Admin> select = getColumnWrapper(wrapper.lambda());
        return context.getAdminMapper().selectPage(page, select);
    }

    private LambdaQueryWrapper<Admin> getColumnWrapper(LambdaQueryWrapper<Admin> wrapper) {
        return wrapper.select(
                Admin::getAdminId
                ,
                Admin::getAdminNum
                ,
                Admin::getAdminRoleId
        );
    }

    @Override
    public Page<Admin> selectLikePaged(@RequestParam(required = false, defaultValue = "1") Integer currentPage,
                                       @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                                       Admin record, String order) {
        Page<Admin> page = new Page<>(currentPage, pageSize);
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        if (!StringUtils.hasText(order)) {
            return context.getAdminMapper().selectPage(page, getColumnWrapper(getQueryWrapper(wrapper, record)));
        }
        wrapper.orderByAsc(CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, order));
        return context.getAdminMapper().selectPage(page, getColumnWrapper(getQueryWrapper(wrapper, record)));
    }

    private LambdaQueryWrapper<Admin> getQueryWrapper(QueryWrapper<Admin> wrapper, Admin record) {
        LambdaQueryWrapper<Admin> lambda = wrapper.lambda();
        if (record.getAdminId() != null) {
            lambda = lambda.eq(Admin::getAdminId, record.getAdminId());
        }
        if (record.getAdminRoleId() != null) {
            lambda = lambda.eq(Admin::getAdminRoleId, record.getAdminRoleId());
        }
        if (record.getAdminNum() != null) {
            lambda = lambda.like(Admin::getAdminNum, record.getAdminNum());
        }
        if (record.getAdminPwd() != null) {
            lambda = lambda.like(Admin::getAdminPwd, record.getAdminPwd());
        }
        return lambda;
    }

    public int count(Admin record) {
        return context.getAdminMapper().selectCount(getQueryWrapper(new QueryWrapper<>(), record));
    }

    @Override
    @EncodeOperation
    public Optional<Admin> updateById(Integer id, @EncodeParam Admin record) {
        record.setAdminId(id);
        int update = context.getAdminMapper().updateById(record);
        if (update > 0) {
            QueryWrapper<Admin> wrapper = new QueryWrapper<>();
            LambdaQueryWrapper<Admin> lambdaQueryWrapper = getColumnWrapper(wrapper.lambda()).eq(Admin::getAdminId, id);
            return Optional.of(context.getAdminMapper().selectOne(getColumnWrapper(lambdaQueryWrapper)));
        }

        return Optional.empty();
    }

    @Override
    public Optional<Admin> selectByNum(String num) {
        LambdaQueryWrapper<Admin> wrapper = new QueryWrapper<Admin>().lambda();
        Admin admin = context.getAdminMapper().selectOne(wrapper.eq(Admin::getAdminNum, num));
        Role role = context.getRoleMapper().selectById(admin.getAdminRoleId());
        LambdaQueryWrapper<RolePermission> rolePermissionLambdaQueryWrapper =
                new QueryWrapper<RolePermission>().lambda().eq(RolePermission::getRolePermissionRoleId,
                        role.getRoleId());
        List<RolePermission> rolePermissions =
                context.getRolePermissionMapper().selectList(rolePermissionLambdaQueryWrapper);
        role.setPermissions(rolePermissions.stream().map(rolePermission -> {
            PermissionMapper permissionMapper = context.getPermissionMapper();
            return permissionMapper.selectById(rolePermission.getRolePermissionPermissionId());
        }).collect(Collectors.toList()));
        admin.setRole(role);
        return Optional.of(admin);
    }

    public boolean updatePwd(Integer id, String curPwd, String updatePwd) {
        Admin admin = context.getAdminMapper().selectById(id);
        if (!encoder.matches(curPwd, admin.getAdminPwd())) {
            throw new BadCredentialsException("认证失败");
        }

        admin.setAdminPwd(encoder.encode(updatePwd));
        return context.getAdminMapper().updateById(admin) > 0;
    }
}
